package com.lin.sunnyweather.utils

import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.preferencesKey
import androidx.datastore.preferences.createDataStore
import com.lin.sunnyweather.SunnyWeatherApplication
import kotlinx.coroutines.flow.map

/**
 * DataStore工具类
 */
object DataStoreUtils {

    private const val PreferenceName = "DataStore"

    private val dataStore by lazy {
        SunnyWeatherApplication.context.createDataStore(
            name = PreferenceName
        )
    }

    private val locationIDKey = preferencesKey<String>("locationIDKey")

    val locationID = dataStore.data.map { preferences ->
        preferences[locationIDKey] ?: ""
    }

    suspend fun setLocationID(locationID: String) {
        dataStore.edit { settings ->
            settings[locationIDKey] = locationID
        }
    }

    private val locationNameKey = preferencesKey<String>("locationNameKey")

    val locationName = dataStore.data.map { preferences ->
        preferences[locationNameKey] ?: ""
    }

    suspend fun setLocationName(locationName: String) {
        dataStore.edit { setting ->
            setting[locationNameKey] = locationName
        }
    }
}